package com.mdoya.filter;

import com.mdoya.domain.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author mdoya
 * @version 1.0
 * @description: SpringMvc过滤器  注意：交给springboot管理，启动类配置 @ServletComponentScan SpringMvc扫描注解
 */
@Slf4j
//@WebFilter("/*") // 拦截所有 注意：/* 正确用法   /** 错误用法
public class GlobaFilter_Back implements Filter {

    private final static AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    /**
     *  跟随Servlet容器启动而init初始化
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("Filter init :{}", filterConfig);
    }

    /**
     *  过滤一切项目资源，两次过滤
     * @param servletRequest servlet请求
     * @param servletResponse Servlet响应
     * @param filterChain 过滤器放行
     * @throws IOException 找不到文件异常
     * @throws ServletException servle服务异常
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
            // 1. 获取请求uri
        String requestURI = request.getRequestURI();
        log.info("请求路径uri: {}",requestURI);
        // 2. 公共资源需要放行
        String[] path = new String[]{"/backend/**","/front/**","/employee/login","/employee/logout"};

        boolean flag = baseResourceCheck(path,requestURI);
        System.out.println("" + flag);
        if (flag){
            log.info("请求公共资源路径: {}",requestURI);
            filterChain.doFilter(request,response); // 公共资源放行
            return;
        }

        // 3. 登录成功放行
        Employee employee = (Employee)request.getSession().getAttribute("employee");
        if (employee != null){
            log.info("登录成功: {}",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        // 4. 拦截响应
//        response.getWriter().write(JSON.toJSONString("NOTLOGIN"));
        response.sendRedirect("/backend/page/login/login.html");
    }

    /**
     *  跟随servlet容器关闭而销毁
     */
    @Override
    public void destroy() {
        log.debug("Filter destroy: {}", "过滤器销毁");
    }

    /**
     *  公共资源符合条件则放行
     * @param path 公共路径uri
     * @param requestURI 请求路径uri
     * @return 布尔类型
     */
    public boolean baseResourceCheck(String[] path, String requestURI) {
        for (String url : path) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){ // 遍历相同路径则返回，否则继续遍历
                return true;
            }
        }
        return false;
    }
}
